﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Chat.Framework;

namespace Chat.Server
{
    internal class HandleClient
    {
        private Socket clientSocket;
        private string clNo;
        Dictionary<string,Socket> client=new Dictionary<string, Socket>();

        public void StartClient(Socket inClientSocket, string clientNo, Dictionary<string, Socket> cList)
        {
            clientSocket = inClientSocket;
            clNo = clientNo;
            client = cList;
            Thread th=new Thread(Chat);
            th.IsBackground = true;
            th.Start();
        }

        private void Chat()
        {
            byte[] bytesFromClient=new byte[4096];
            string dataFromClient;
            string msgTemp = null;
            byte[] bytesSend=new byte[4096];
            bool isListen = true;

            while (isListen)
            {
                try
                {
                    int len = clientSocket.Receive(bytesFromClient);
                    if (len > -1)
                    {
                        dataFromClient= EncryptionAndDecryption
                            .TripleDESDecrypting(Encoding.UTF8.GetString(bytesFromClient,0,len));
                        if (!string.IsNullOrWhiteSpace(dataFromClient))
                        {
                            dataFromClient = dataFromClient.Substring(0, dataFromClient.LastIndexOf("$"));
                            if (!string.IsNullOrWhiteSpace(dataFromClient))
                            {
                                BroadCast.PushMessage(dataFromClient, clNo, true, client);
                                msgTemp = $"{clNo}:{dataFromClient}\t\t{DateTime.Now.ToString()}";
                                string newMsg = msgTemp;
                                File.AppendAllText($"{AppDomain.CurrentDomain.BaseDirectory}MessageRecords.txt",
                                    $"{newMsg}\r\n",Encoding.UTF8);
                            }
                            else
                            {
                                isListen = false;
                                client.Remove(clNo);
                                clientSocket.Close();
                                clientSocket = null;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    isListen = false;
                    client.Remove(clNo);
                    clientSocket.Close();
                    clientSocket = null;
                    File.AppendAllText($"{AppDomain.CurrentDomain.BaseDirectory}Exception.txt", ex.Message);
                }
            }
        }
    }
}